package javango.conf;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import javango.api.Settings;
import javango.core.contextprocessors.ContextProcessor;
import javango.middleware.Middleware;

/**
 * Wrapper around client's Settings class used in javango runtime. Main differnce
 * compared to Settings is presence of injector and therefore capability to instantiate
 * middleware classes, etc.
 *
 */
@Singleton
public class RuntimeSettings {
    
    private javango.api.Settings settings;
    private Injector injector;
    private List<Middleware> middlewareInstances;
    private List<ContextProcessor> contextProcessorsInstances;

    @Inject
    public RuntimeSettings(Settings settings, Injector injector) {
        assert settings.isValid();
        this.settings = settings;
        this.injector = injector;
    }
    
    public List<Middleware> getMiddlewares() {
        if (middlewareInstances == null) {
            middlewareInstances = new ArrayList<Middleware>();
            for (Class<? extends Middleware> clazz : settings.getMiddlewareClasses()) {
                middlewareInstances.add(injector.getInstance(clazz));
            }
        }
        return middlewareInstances;
    }

    public List<ContextProcessor> getContextProcessors() {
        if (contextProcessorsInstances == null) {
            contextProcessorsInstances = new ArrayList<ContextProcessor>();
            for (Class<? extends ContextProcessor> clazz : settings.getContextProcessors()) {
                contextProcessorsInstances.add(injector.getInstance(clazz));
            }
        }
        return contextProcessorsInstances;
    }

    public Settings getSettings() {
        return settings;
    }

}
